<template>
  <div class="content">
    <!-- 公共组件-每个页面必须引入 -->
    <public-module></public-module>
	<div class="integralCar-page">
	        <div class="no-data" v-if="(!upGoodsList || upGoodsList.length == 0) && !loading">
	            <img src="https://pic.moresu.com/FjDoFccPPB_tAjSFWePRjGJh9B8X" mode="aspectFit" style="width:150px;height:200px;object-fit: contain;display: inline-block;"/>
	            <div style="color:#888;font-size:14px;text-align: center;">
	                购物车空空如也，<span class="no-data-btn" @click="toHome">去逛逛</span>吧~
	            </div>
	        </div>
	        <div class="car-list" v-else-if="!loading">
	            <u-checkbox-group v-model="result" @change="onChangeItem" >
					<u-swipe-action>
						<div class="car-item" v-for="(item,index) in upGoodsList" :key="index">
								<u-swipe-action-item :options="options1" @click="delItem(item)"  ref="swipeAction">
									<div class="car-goods">
										<u-checkbox :name="item.goodsId" activeColor="#ff4600" shape="circle"></u-checkbox>
										<div class="goods-img" @click="toIntegralGoodsInfo(item.goodsId)">
											<img :src="item.goodsImage" mode="aspectFit" style="width:80px;height:80px;object-fit: contain"/>
										</div>
										<div class="goods-text" @click.self="toIntegralGoodsInfo(item.goodsId)">
											<div class="goods-name">{{ item.goodsName }}</div>
											<div class="goods-price">
												<span style="color:#ff4600;">{{ item.goodsPrice }} 积分</span>
												<u-number-box v-model="item.goodsNum"  @change="onChangeGoodsNum(index,$event)" integer></u-number-box>	
											</div>
										</div>
									</div>
								</u-swipe-action-item>
						</div>
	
	                <div style="padding:0px 30px" v-if="downGoodsList.length > 0">
	                    <u-divider text="已失效商品"></u-divider>
	                </div>
	
	                <div class="car-item disabled" v-for="item in downGoodsList" :key="item.goodsId">
	                   <u-swipe-action-item :options="options1" ref="swipeAction">
	                        <div class="car-goods">
								<u-checkbox :name="item.goodsId" disabled shape="circle"></u-checkbox>
	                            <div class="goods-img" style="position: relative">
	                                <div style="color:#fff;text-align: center;height:24px;width:100%;position:absolute;bottom: 12px;background: rgba(0,0,0,0.5);font-size: 12px;line-height: 24px;">失效</div>
	                                <img :src="item.goodsImage" mode="aspectFit" style="width:80px;height:80px;object-fit: contain"/>
	                            </div>
	                            <div class="goods-text">
	                                <div class="goods-name" style="color:#aaa">{{ item.goodsName }}</div>
	                                <div class="goods-price">
	                                    <span style="color:#aaa;">{{ item.goodsPrice }} 积分</span>
										<u-number-box v-model="item.goodsNum"  disabled integer></u-number-box>	
	                                </div>
	                            </div>
	                        </div>
	                    </u-swipe-action-item>
	                </div>
					</u-swipe-action>
	            </u-checkbox-group>
	
	
	        </div>
	        <div class="car-bottom" :style="{bottom:50+systemInfo.bottomSafeAreaHeight+'px'}">
	            <div>
					<u-checkbox-group v-model="checkedAll" @change="onChange">
						<u-checkbox   label="全选" name="1" activeColor="#ff4600" shape="circle"></u-checkbox>
					</u-checkbox-group>
	                
	            </div>
	            <div class="count" style="margin-right:10px">总计：<span class="price">{{ allPrice }}<span style="font-size:12px;padding-left:5px">积分</span></span></div>
	            <div class="bottom-btn">
	                <u-button :disabled="result.length == 0 || allPrice > myIntegral" type="warning" shape="circle" color="linear-gradient(to right, #ff4600, #fd7505)"  customStyle="{'height':'36px','margin-left':'16px','line-height': '36px'}" @click="toJianShuang" :loading="btnLoadin">
	                    {{ allPrice > myIntegral ? '余额不足' : '去结算' }}</u-button>
	            </div>
	        </div>
	    </div>
		
	   <bnavbar ref="bnavbar"></bnavbar>
	
  </div>
</template>

<script>
  import bnavbar from './components/b-navbar';
  import{integralOrderConfirm,delCartGoods,integralUserInfo,editCartGoods,inquiryCartInfo} from '@/config/points.js'
   import {pageSeo} from '@/config/api.js'
  import store from '@/store';
  export default {
    components: {
       bnavbar

    },
    data() {
      return {
			showRight:false,
			downGoodsList:[],
			upGoodsList:[],
			loading: true,

			show:false,
			result:[],
			checkedAll:[],
			count:'',
			allPrice:0,
			chooselist:[],
			myIntegral:0,
			btnLoadin:false,
			carInfo:0,
			active:3,
			storeUserInfo:{},
			systemInfo:{
			    bottomSafeAreaHeight :uni.getSystemInfoSync().safeAreaInsets.bottom,
				screenHeight:uni.getSystemInfoSync().windowHeight-uni.getSystemInfoSync().safeArea.top-44,
			},
			options1: [
					{
						text: '删除',
						style: { backgroundColor: '#f56c6c' } ,
					}
				],
			showAction:true
      }
    },

	async onLoad(options) {
    	await this.$onLaunched;	
	
        this.getList();
		store.dispatch('userInfo').then(()=>{
			this.storeUserInfo = store.state.userInfo;
			if(this.storeUserInfo.userId){
				this.getMyIntegral();
			}
		})
		this.$refs.bnavbar.init(3,'#FC7032')
    },
    async onShow() {
		// #ifdef H5
		pageSeo({pageType: 'indexPage'}).then((res)=>{
			document.title = res.pageTitle;
		})
		// #endif	
	},
	
    methods: {
		
		toHome(){
			uni.navigateTo({
				url: "/pagesIntegral/integral"
			})
		},
		toJianShuang(){
			this.btnLoadin = true;
			let goodsId = [];
			let goodsNum = [];
			let data = {};
			data.goodsList = [];
			this.chooselist.forEach((el)=>{
				goodsId.push(el.goodsId)
				goodsNum.push(el.goodsNum)
				data.goodsList.push({goodsId:el.goodsId,goodsNum:el.goodsNum})
			})
			integralOrderConfirm(data).then(()=>{
				this.btnLoadin = false;
				uni.navigateTo({
					url: '/pagesIntegral/intergralOrderSettlement?goodsId='+ goodsId.join(",") +'&goodsNum='+ goodsNum.join(",")+'&buyType=1'
				})
				
			}).catch(()=>{
				this.btnLoadin = false;
			})

		},

		delItem(item){
			console.log(item)
			uni.showModal({
				title: '删除商品',
				content: '确认要删除此商品吗？',
				success:  (res)=> {
						if (res.confirm) {
							delCartGoods({cartIds:[item.cartId]}).then(()=>{
								uni.$u.toast("删除成功!");
								store.dispatch('getInquiryCartInfo')
								this.getList().then((res)=>{
									let dIndex  = -1
									console.log("this.upGoodsList",this.upGoodsList)
									console.log("this.result",this.result)
									for(let i = 0; i<this.result.length; i++){
										let index =  this.upGoodsList.findIndex((ee)=>{
											return  ee.goodsId == this.result[i]
										})
										if(index == -1){
											// dIndex = i
											this.result.splice(i,1);
											this.chooselist.splice(i,1);
											break
										}
									}
									for(let i = 0; i<this.$refs['swipeAction'].length; i++){
										this.$refs['swipeAction'][i].closeHandler()
									}
									// this.result.splice(dIndex,1);
									// this.chooselist.splice(dIndex,1);
									this.onChangeItem(this.result)
									
								});
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
				}	
			})
		},

		//积分余额
		getMyIntegral(){
			integralUserInfo().then((res)=>{
				this.myIntegral = res.userInfo.balance*1;
			})
		},

		toIntegralGoodsInfo(goodsId){
			uni.navigateTo({
				url: '/pagesIntegral/integralGoodsInfo?goodsId='+goodsId
			})
			
		},

		//全选
		onChange(e){
			this.checkedAll = e
			if(this.checkedAll.length>0){
				this.chooselist = JSON.parse(JSON.stringify(this.upGoodsList));
				this.result = []
				this.upGoodsList.forEach((el)=>{
					this.result.push(el.goodsId)
				})
			}else{
				this.result = []
				this.chooselist = [];
			}
			this.countJifeng();
		},

		//修改购物车数量
		onChangeGoodsNum(index,e){
			let data = e.value;
			editCartGoods({cartId:this.upGoodsList[index]['cartId'],goodsNum:data}).then(()=>{
				store.dispatch('getInquiryCartInfo')
				this.getList().then(()=>{
					this.onChangeItem(this.result)
				})	
				
			})
		},

		//计算总积分
		countJifeng(){
			let allPrice = 0;
			this.chooselist.forEach((el)=>{
				allPrice = allPrice + (parseFloat(el.goodsPrice)*parseFloat(el.goodsNum));
			});
			this.allPrice = parseFloat(allPrice.toFixed(2))*1;
		},

		//切换选中项
		onChangeItem(e){
			console.log("e",e)
			this.result = e;
			console.log("this.result",this.result)
			this.checkedAll = this.result.length == this.upGoodsList.length ? ['1']:[],
			this.$forceUpdate()
			let data = e;
			this.chooselist = [];
			data.forEach((el)=>{
				let item = this.upGoodsList.find((e)=>{
					return el == e.goodsId
				});
				this.chooselist.push(item);
			});
			this.countJifeng();
		},



		//获取列表
		getList(){
			this.loading = true;
			return inquiryCartInfo().then((res)=>{
				this.loading = false;
				this.upGoodsList = res.upGoodsList;
				this.downGoodsList = res.downGoodsList;
				this.count = parseFloat(res.cartGoodsNum);
				console.log("this.upGoodsList",!this.upGoodsList);
			}).catch(()=>{
				// 加载状态结束
				// this.loading = false;
				// this.finished = true;
			})
		},
		
	}
	

  }
</script>
<style>
	
</style>

<style lang="scss">
@import '@/style/common.scss';
.integralCar-page{
  overflow: auto;
  padding-bottom:120px;
}
.integralCar-page .no-data{
  padding-top:30px;
  text-align: center;
  cursor: pointer;
}
.integralCar-page .no-data-btn{
  color:#1989fa;
  padding:0 5px;
  text-decoration: underline;
}
.integralCar-page .car-list{
  min-height: 100%;
  padding:12px;
  padding-bottom: 20px;
  .car-item{
    background: #fff;
    border-radius: 8px;
    padding-left:12px;
    margin-bottom:12px;
	overflow: hidden;
	z-index: 0;
	position: relative;
    .car-goods{
      display: flex;
      align-items:center;
      justify-content:flex-start;
      .goods-text{
        flex:1;
        height:124px;
        position: relative;
        padding:12px;
        .goods-price{
          display: flex;
          align-items:center;
          justify-content:space-between;
          font-size:14px;
          position: absolute;
          bottom:12px;
          width:calc(100% - 24px)
        }
      }
      .goods-img{
        margin-left:15px;
        height:124px;
        padding:12px 0;
      }
      .goods-name{
        color:#222;
        font-size:14px;
        word-break: break-all;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }
    }
    .item-del{
      background:#ff4600;
      color:#fff;
      text-align: center;
      line-height: 124px;
      width:65px;
      height:124px;
    }
  }
}
.integralCar-page  .car-bottom{
  bottom:50px;
  position: fixed;
  width:100%;
  height:50px;
  background: rgba(255,255,255,0.95);
  z-index: 3;
  display: flex;
  align-items:center;
  justify-content:flex-start;
  font-size:14px;
  padding:0 12px;
  border-bottom:1px solid #eee;
  .count{
    color:#222;
    text-align: right;
    flex:1;
    .price{
      color:#ff4600
    }
  }
}
.integralCar-page  .car-bottom:before {
  content: "";
  position: absolute;
  z-index: 1;
  pointer-events: none;
  background-color: #ddd;
  height: 1px;
  left: 0;
  right: 0;
  top: 0;
  -webkit-transform: scaleY(.5);
  -webkit-transform-origin: 50% 0;
}
</style>


    
    
